<?php

/**
 * @author Nemo <nemo.xiaolan@gmail.com>
 * @package #.lib.dispatcher.dispatcher
 * 有两种模式
 *  1. normal: index.php?-=home/index
 *  2. pathinfo: /home/list/1.html?page=2
 */

class Dispatcher {
    
    static public $type = "normal";
    
    static public $delimiter = "?-=";
    
    static public $extra = "";
    
    static public function work() {
        $uri = $_SERVER["REQUEST_URI"];
        /**
         * Normal 模式
         */
        if(strpos($uri, self::$delimiter)) {
            self::$type = "normal";
            $action = self::normal($uri);
        /**
         * Pathinfo模式
         */
        } else {
            $action = self::pathinfo($uri);
        }
        
        return $action;
    }
    
    static private function normal($uri) {
        $uri = end(explode(self::$delimiter, $uri));
        list($action, $params) = explode("?", $uri);
        $action = explode("/", $action);
        $group = array_shift($action);
        $name = array_shift($action);
        return array(
            "group" => $group,
            "name"  => $name,
            "params"=> $action,
            "get" => $params
        );
    }
    
    static private function pathinfo($uri) {
        $server = str_ireplace("index.php", "", $_SERVER["PHP_SELF"]);
        $uri = end(explode($server, $uri));
        list($action, $params) = explode("?", $uri);
        $action = explode("/", $action);
        $group = array_shift($action);
        $name = array_shift($action);
        $params = explode("&", $params);
        
        $p = array();
        foreach($params as $param) {
            list($k, $v) = explode("=", $param);
            $p[$k] = $_GET[$k] = $v;
        }
        return array(
            "group" => $group,
            "name"  => $name,
            "params"=> $action,
            "get" => $p
        );
    }
    
    static public function get_url($action) {
        global $C;
        switch(self::$type) {
            case "normal":
                $uri = self::$delimiter.$action;
                break;
            case "pathinfo":
                $uri = $action;
                break;
        }
        return $uri.self::$extra;
    }
    
}

/**
 * Shortcut
 */
if(!function_exists("u")) {
    function u($action) {
        return Dispatcher::get_url($action);
    }
}